package com.thx.common.struts2;

import com.thx.common.orm.model.ExtendPropertyEntity;
import com.thx.common.orm.model.Property;
import com.thx.common.orm.model.Template;
import com.thx.common.service.ExtendPropertyComponent;
import com.thx.common.util.DeepCopyUtil;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 扩展属性action，在开发中有扩展属性需求的实体的action需要继承.
 *
 * @author calonlan
 */
public class ExtendPropertyAction<T extends ExtendPropertyEntity> extends CurdAction<T> {

  private static final long serialVersionUID = -6010540817518347769L;

  @Autowired
  ExtendPropertyComponent component;

  @Override
  public String list() {
    String returnStr = super.list();
    if (list != null && list.size() > 0) {
      List<Property> props = list.get(0).getProperties();
      // 调用了ExtendPropertyManger或者调用了ExtendPropertyComponent，
      // 在父类中已经给实体的List<Property>赋过值的直接返回
      if (props != null) {
        return returnStr;
      } else {
        // 否则，重新赋值
        Template template = component.findTempalteByEntityClass(list.get(0).getClass().getName());
        if (template.getId() != null) {
          List<Property> properties;
          for (T entity : list) {
            properties = component.findPropertiesByTemplateIdAndEntityId(
                template.getId(), entity.getId().toString());
            try {
              //深度复制properties，否则每个实体对象的properties都是一样的
              properties = DeepCopyUtil.deepCopy(properties);
            } catch (ClassNotFoundException ex) {
              ex.printStackTrace();
            } catch (IOException ex) {
              ex.printStackTrace();
            }
            entity.setProperties(properties);
            entity.setTemplate(template);
          }
        }

      }
    }
    return returnStr;
  }

  @Override
  public String input() {
    String returnStr = super.input();
    //如果是新增，给实体赋值扩展属性
    if (id == null || id.length() <= 0) {
      Template template = component.findTempalteByEntityClass(entity.getClass().getName());
      List<Property> list = component.findPropertiesByTemplateId(template.getId());
      entity.setTemplate(template);
      entity.setProperties(list);
    }
    return returnStr;
  }

  @Override
  public String save() {

    Map<String, String[]> paramMap = getRequest().getParameterMap();
    if (StringUtils.isBlank(id)) {
      // 新增
      component.setEntityExtendPropertyVals(entity, id, paramMap);
    } else {
      // 修改
      component.setEntityExtendPropertyVals(baseMgr.get(id), id, paramMap);
    }
    return super.save();
  }

}
